<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class Source extends Controller
{
    public function upload(Request $request)
    {
        if (!$request->input('base64')) {
            return response()->json([
                'code' => 500,
                'msg' => '缺少数据',
                'data' => []
            ]);
        }
        return response()->json([
            'code' => 200,
            'msg' => '',
            'data' => (new \App\Db\Source())->upload($request->input('base64'))
        ]);
    }

    public function getSource($id)
    {
        if (!$id) {
            return response()->json([
                'code' => 500,
                'msg' => '请传入id',
                'data' => []
            ]);
        }
        $source = (new \App\Db\Source())->getSource($id);
        if ($source) {
            return response(base64_decode(explode('base64,', $source)[1]), 200)->header('Content-Type', 'image/png');
        } else {
            return response()->json([
                'code' => 500,
                'msg' => '没有资源',
                'data' => []
            ]);
        }
    }

    public function getSourceList(Request $request)
    {
        if (!$page = $request->input('page')) {
            $page = 1;
        }
        if (!$limit = $request->input('limit')) {
            $limit = 20;
        }
        list($data, $count) = [
            DB::table('source')->where('is_del', '=', 0)->select(['id', 'create_time'])->skip(($page - 1) * $limit)->limit($limit)->orderByDesc('create_time')->get()->toArray(),
            DB::table('source')->where('is_del', '=', 0)->count()
        ];

        return response()->json([
            'code' => 200,
            'msg' => '',
            'data' => [
                'count' => $count,
                'data' => $data
            ]
        ]);
    }

    public function deleteSource(Request $request)
    {
        if (!$id = $request->input('id')) {
            return response()->json([
                'code' => 500,
                'msg' => '没有 id',
                'data' => []
            ]);
        }
        return response()->json([
            'code' => 200,
            'msg' => '',
            'data' => DB::table('source')->where('id', '=', $id)->delete()
        ]);
    }
}
